package mm.core;

import java.util.HashMap;
import java.util.Map;

public class Factory {
	
	private static final Map<Class, Object> serviceMap=new HashMap<Class, Object>();

	public static <T> T get(Class<T> clazz) {
		T object=clazz.cast(serviceMap.get(clazz));
		if(object==null){
			if(clazz.isInterface()){
				String implementClassName=clazz.getName()+"Impl";
				try {
					Class implementClass = Class.forName(implementClassName);
					object=clazz.cast(implementClass.newInstance());
				} catch (Exception e) {
					throw new RuntimeException("can't instance class "+implementClassName, e);
				}
			}else{
				try {
					object=(T) clazz.newInstance();
				} catch (Exception e) {
					throw new RuntimeException("can't instance class "+clazz.getName(), e);
				}
			}
			serviceMap.put(clazz, object);
		}
		return object;
	}

}
